package homework9.Action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import homework9.Bean.School;
import homework9.Bean.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CoderXshuai
 */
public class StudentAction extends ActionSupport implements ModelDriven {
    private static final SessionFactory FACTORY;

    static {
        Configuration configuration = new Configuration();
        configuration.configure();
        FACTORY = configuration.buildSessionFactory();
    }

    private Student student = new Student();
    private School school = new School();
    private List<Student> stulist = new ArrayList<>();
    private List<School> schoolList = new ArrayList<>();

    public static Session getSession() {
        return FACTORY.openSession();
    }

    @Override
    public Object getModel() {
        // TODO Auto-generated method stub
        return student;
    }

    public String Index() {
        final Session session = getSession();
        Query studentQuery = session.createQuery("from Student ");
        stulist = studentQuery.list();
        return "Index";
    }

    public String Add() {
        final Session session = getSession();
        student.getSchoolList().addAll(schoolList);
        for (School school : schoolList) {
            school.setStudent(student);
        }
        session.save(student);
        Query studentQuery = session.createQuery("from Student ");
        stulist = studentQuery.list();
        session.beginTransaction().commit();
        return "Add";
    }

    public String Get() {
        final Session session = getSession();
        Query studentQuery = session.createQuery("from Student ");
        stulist = studentQuery.list();
        return "Get";
    }


    public String Edit() {
        return "Edit";
    }

    public String Del() {
        return "Del";
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public List<Student> getStulist() {
        return stulist;
    }

    public void setStulist(List<Student> stulist) {
        this.stulist = stulist;
    }

    public List<School> getSchoolList() {
        return schoolList;
    }

    public void setSchoolList(List<School> schoolList) {
        this.schoolList = schoolList;
    }
}
